package com.ygqh.baby.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.po.YgWholesaler;
import com.ygqh.baby.mapper.YgWholesalerMapper;
import com.ygqh.baby.service.ScheduleJobService;
import com.ygqh.baby.service.YgWholesalerPrebillRecordService;
import com.ygqh.baby.service.YgWholesalerService;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import com.ygqh.baby.po.YgWholesalerExample;

/**
 * @author Ss
 */
@Service
public class YgWholesalerServiceImpl implements YgWholesalerService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private final ExecutorService executorService = Executors.newFixedThreadPool(2);

	@Autowired
	private YgWholesalerMapper ygWholesalerMapper;
	@Autowired
	private ScheduleJobService scheduleJobService;
	@Autowired
	private YgWholesalerPrebillRecordService ygWholesalerPrebillRecordService;

	@Override
	public List<YgWholesaler> find() {
		YgWholesalerExample example = new YgWholesalerExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygWholesalerMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		YgWholesalerExample example = new YgWholesalerExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygWholesalerMapper.countByExample(example);
	}

	@Override
	public YgWholesaler findById(Long id) {
		return ygWholesalerMapper.selectByPrimaryKey(id);
	}

	@Override
	public int save(YgWholesaler ygWholesaler) {
		return ygWholesalerMapper.insertSelective(ygWholesaler);
	}

	@Override
	public int update(YgWholesaler ygWholesaler) {
		return ygWholesalerMapper.updateByPrimaryKeySelective(ygWholesaler);
	}

	@Override
	public ResultSet<YgWholesaler> search(QueryInfo queryInfo, String wholesalerName) {
		int count = ygWholesalerMapper.countSuper(wholesalerName);
		if (count == 0) {
			return new ResultSet<>();
		}
		List<YgWholesaler> list = this.findList(queryInfo, wholesalerName);
		return new ResultSet<>(count, list);
	}

	@Override
	public List<YgWholesaler> findList(QueryInfo queryInfo, String wholesalerName) {
		return ygWholesalerMapper.selectSuper(queryInfo, wholesalerName);
	}

	@Override
	public boolean validateNameIsUsable(String wholesalerName, Long id) {
		Assert.isTrue(StringUtils.isNotBlank(wholesalerName), "批发商名称不能为空");
		return !ygWholesalerMapper.validateNameIsUsable(wholesalerName, id);
	}

	@Override
	public Message edit(YgWholesaler wholesaler) {
		this.validateEditParam(wholesaler);
		if (wholesaler.getId() != null) {
			wholesaler.setShopNo(null);
			this.update(wholesaler);
		} else {
			wholesaler.setCreateBy(wholesaler.getUpdateBy());
			wholesaler.setCreateTime(wholesaler.getUpdateTime());
			this.save(wholesaler);
		}

		//添加结算服务
		this.addJobAsync(wholesaler.getId());
		return Message.success(null);
	}

	private void addJobAsync(Long wholesalerId) {
		executorService.execute(() -> {
			YgWholesaler wholesaler = this.findById(wholesalerId);
			ygWholesalerPrebillRecordService.addPrebillOrderRecordPastTime(wholesaler);
			Date executeTime;
			int interval = wholesaler.getBillingCycle();
			if (interval >= Constant.STANDARD_DAYS_OF_MONTH) {
				executeTime = DateConvertUtils.addMonth(DateConvertUtils.getMonthStartDate(wholesaler.getUpdateTime()), 1);
			} else {
				executeTime = DateConvertUtils.addDay(DateConvertUtils.getDateStart(wholesaler.getUpdateTime()), interval);
			}
			// 准点延时两小时执行
			executeTime = DateConvertUtils.addMinute(executeTime, 120);
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("wholesalerId", wholesaler.getId());
			try {
				scheduleJobService.addJob(YgQuartzJob.Wholesaler, wholesaler.getId().toString(), executeTime, dataMap, wholesaler.getUpdateBy(), null);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		});
	}

	@Override
	public void updateRechargePrice(YgWholesaler wholesaler) {
		ygWholesalerMapper.updateRechargePrice(wholesaler);
	}

	@Override
	public void updateAmountDuePrice(YgWholesaler wholesaler) {
		ygWholesalerMapper.updateAmountDuePrice(wholesaler);
	}

	@Override
	public void updateAmountPrice(YgWholesaler wholesaler) {
		ygWholesalerMapper.updateAmountPrice(wholesaler);
	}

	@Override
	public List<Map<String, String>> findPlatformList() {
		return ygWholesalerMapper.selectPlatformList();
	}

	private void validateEditParam(YgWholesaler wholesaler) {
		Assert.isTrue(this.validateNameIsUsable(wholesaler.getWholesalerName(), wholesaler.getId()), "批发商名称已存在");
		Assert.notNull(wholesaler.getBillingType(), "结算类型不能为空");
		Assert.notNull(wholesaler.getBillingCycle(), "结算周期不能为空");
		Assert.isTrue(wholesaler.getBillingCycle() > 0, "结算周期不合法");
		if (wholesaler.getId() == null) {
			Assert.isTrue(StringUtils.isNotBlank(wholesaler.getShopNo()), "店铺编号不能为空");
		}
	}

}

